package com.zrgg.futuwen.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.xcc.wavzmp3.MP3Recorder;
import com.zrgg.futuwen.R;
import com.zrgg.futuwen.utils.Logger;

import java.io.File;
import java.io.InputStream;

/**
 * Created by 磁磁帅 on 2017/8/3.
 * 描述：
 */
public class SoundRecordDialog extends PopupWindow implements View.OnClickListener {
    private View textConfirm;
    private ImageView icon;
    private TextView btnText;
    private Bitmap bitmaps[];

    public SoundRecordDialog(Context context) {
        super(context);
        setBackgroundDrawable(null);
        this.context = context;

        LayoutInflater inflater = LayoutInflater.from(context);
        conentView = inflater.inflate(R.layout.dialog_sound_record, null);
        // 设置SelectPicPopupWindow的View
        this.setContentView(conentView);
        // 设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        // 设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        // 设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        this.setOutsideTouchable(true);

        // 刷新状态
        this.update();

        initView();

        setBackgroundDrawable(new BitmapDrawable());
        conentView.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                //if (i == KeyEvent.KEYCODE_BACK) dismiss();
                return false;
            }
        });
    }

    private void initView() {
        textConfirm = conentView.findViewById(R.id.textConfirm);
        icon = (ImageView) conentView.findViewById(R.id.icon);
        btnText = (TextView) conentView.findViewById(R.id.btnText);

        icon.setOnClickListener(this);
        textConfirm.setOnClickListener(this);
        conentView.findViewById(R.id.textCancel).setOnClickListener(this);

        //加载图片
        try {
            InputStream is = context.getAssets().open("sound.png");
            Bitmap bitmap = BitmapFactory.decodeStream(is);
            bitmaps = new Bitmap[2];
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            //开始裁剪图片
            bitmaps[0] = Bitmap.createBitmap(bitmap, 0, 0, width, width);
            bitmaps[1] = Bitmap.createBitmap(bitmap, 0, height - width, width, width);
            icon.setImageBitmap(bitmaps[0]);
        } catch (Exception e) {
            if (Logger.isDebug) e.printStackTrace();
        }
        btnText.setText(R.string.kaishiluyin);
        textConfirm.setEnabled(false);
    }

    private Context context;
    private View conentView;

    //显示
    public void showPopupWindow(View parent) {
        if (!this.isShowing()) {
            //showAtLocation(parent, Gravity.LEFT, 0, 0);
            //showAsDropDown(parent);
            showAtLocation(parent, Gravity.TOP, 0, 0);
        } else {
            super.dismiss();
        }
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.textConfirm: {//返回录音文件
                if (onSoundRecordListener != null) onSoundRecordListener.onSoundRecord(fileName);
                dismiss();
            }
            break;
            case R.id.textCancel: {//取消
                if (mp3Recorder != null) {
                    if (type == 1) mp3Recorder.stop();
                    mp3Recorder.deleteFile();
                }
                dismiss();
            }
            break;
            case R.id.icon: {//开始或停止录音
                if (type == 0) {//开始录音
                    type = 1;
                    btnText.setText(R.string.tingzhiluyin);
                    if (bitmaps != null) icon.setImageBitmap(bitmaps[1]);

                    fileName = MP3Recorder.getFileName();
                    mp3Recorder = new MP3Recorder(new File(fileName));
                    try {
                        mp3Recorder.start();
                    } catch (Exception e) {
                        if (Logger.isDebug) e.printStackTrace();
                    }
                    handler.sendEmptyMessageDelayed(0, 2000);
                } else if (type == 1) {//停止录音
                    type = 2;
                    btnText.setText(R.string.luyinwancheng);
                    textConfirm.setEnabled(true);
                    if (bitmaps != null) icon.setImageBitmap(bitmaps[0]);
                    mp3Recorder.stop();
                } else {//重新录音
                }
            }
            break;
        }
    }

    public void dismiss() {
        handler.removeCallbacksAndMessages(null);
        super.dismiss();
    }

    private String fileName;
    private MP3Recorder mp3Recorder;
    private int type = 0;//0等待录音，1正在录音，2录音完成
    private OnSoundRecordListener onSoundRecordListener;
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {//录音失败
            if (mp3Recorder != null && !mp3Recorder.isSucc()) {
                Toast.makeText(context, "录音失败，请重试", Toast.LENGTH_SHORT).show();
                mp3Recorder.stop();
                mp3Recorder.deleteFile();
                mp3Recorder = null;
                type = 0;
                if (bitmaps != null) icon.setImageBitmap(bitmaps[0]);
                btnText.setText(R.string.kaishiluyin);
            }
        }
    };

    public SoundRecordDialog setOnSoundRecordListener(OnSoundRecordListener onSoundRecordListener) {
        this.onSoundRecordListener = onSoundRecordListener;
        return this;
    }

    public interface OnSoundRecordListener {
        void onSoundRecord(String fileStr);
    }
}
